package com.wzh.dao.daoImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.wzh.utils.DataBaseUtil;
import com.wzh.pojo.Contact;
import com.wzh.dao.ContactDao;

public class ContactDaoImpl implements ContactDao {

	private static Connection conn;

	@Override
	public int add(Contact contact) {
		conn = new DataBaseUtil().getConnection();
		String sql = "insert into contact_info (name,telephone,address) values (?,?,?)";
		PreparedStatement ppst;
		int status = 0;
		try {
			ppst = conn.prepareStatement(sql);
			ppst.setString(1, contact.getName());
			ppst.setString(2, contact.getTelephone());
			ppst.setString(3, contact.getAddress());
			status = ppst.executeUpdate();
		} catch (SQLException e) {
			System.out.println("添加异常");
			e.printStackTrace();
		}
		return status;
	}

	@Override
	public int delete(int id) {
		conn = new DataBaseUtil().getConnection();
		String sql = "delete from contact_info  where id = ?";
		PreparedStatement pstmt;
		int status = 0;
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id+"");
			pstmt.execute();
		} catch (SQLException e) {
			System.out.println("删除异常");
			e.printStackTrace();
		}
		return status;

	}

	@Override
	public List<Contact> queryAllContacts() {
		conn  = new DataBaseUtil().getConnection();
		ResultSet rs = null;
		String sql = "select id,name,telephone,address from contact_info";
		List<Contact> contactList = new ArrayList<Contact>();
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
		    rs = pstmt.executeQuery();
			while(rs.next()){
				Contact contact = new Contact();
				contact.setId(rs.getInt("id"));
				contact.setName(rs.getString("name"));
				contact.setTelephone(rs.getString("telephone"));
				contact.setAddress(rs.getString("address"));
				contactList.add(contact);
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return contactList;
	}

	@Override
	public int updateContact(int id, Contact newContact) {
		conn  = new DataBaseUtil().getConnection();
		String sql = "update contact_info set  telephone = ?, name = ? where id = ?";
		int status = 1;
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, newContact.getTelephone());
			pstmt.setString(2, newContact.getName());
			pstmt.setString(3, id + "");
			status = pstmt.executeUpdate();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return status;
	}
}
